/*   
 * 文件名：UserController.java
 * 版权：〈Copy Ruantu〉
 * 描述：〈描述〉
 * 修改人：〈MengFanding〉
 * 修改时间：2017 上午10:58:58
 * 修改单号：〈修改单号〉
 * 修改内容：〈修改内容〉
 */

package com.ruantu.clothing.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruantu.clothing.entity.JsonResponseMessage;
import com.ruantu.clothing.entity.User;
import com.ruantu.clothing.service.UserService;
import com.ruantu.clothing.util.MD5;

/**
 * UserController
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 用户登录
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),
                MD5.d5(MD5.d5(user.getPassWord() + "ruantu")));
        try {
            token.setRememberMe(user.isRem());
            subject.login(token);
            Session session = subject.getSession();
            User u = userService.login(user.getUserName());
            session.setAttribute("info", u);
            return "redirect:/bbqq/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            HttpSession session1 = request.getSession();
            session1.setAttribute("errorMsg", "用户名或密码错误！");
            return "redirect:/bbqq/login.jsp";
        }

    }

    /**
     * 零售登陆
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/logins")
    public String logins(User user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),
                MD5.d5(MD5.d5(user.getPassWord() + "ruantu")));
        try {
            token.setRememberMe(user.isRem());
            subject.login(token);
            Session session = subject.getSession();
            User u = userService.login(user.getUserName());
            session.setAttribute("info", u);
            return "redirect:/bbqq/sale.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            HttpSession session1 = request.getSession();
            session1.setAttribute("errorMsg", "用户名或密码错误！");
            return "redirect:/bbqq/retail.jsp";
        }

    }

    /**
     * 登出
     *
     * @return
     */
    @RequestMapping("/loginout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
        return "redirect:/bbqq/login.jsp";
    }

    /**
     * 零售登出
     *
     * @return
     */
    @RequestMapping("/loginouts")
    public String logouts() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
        /* System.out.println("登出"); */
        return "redirect:/bbqq/retail.jsp";
    }

    /**
     * 保存用户
     *
     * @param user
     * @return
     */

    @RequestMapping("/addUser")
    @ResponseBody
    public JsonResponseMessage tianUser(User user, HttpSession session, int[] array) {
        JsonResponseMessage msg = new JsonResponseMessage();
        User u = (User) session.getAttribute("info");
        try {
            user.setPassWord(MD5.d5(MD5.d5(user.getPassWord() + "ruantu")));
            List<User> list = userService.tianUser(user, array);
            if (list != null) {
                msg.setCode(0);
                msg.setData(list);
                logger.info("新增用户成功，执行人" + u.getUserName());
            } else {
                msg.setCode(1);
                logger.info("新增用户失败，执行人" + u.getUserName());
            }
        } catch (Exception e) {
            logger.error("新增用户异常，执行人" + u.getUserName());
            e.getStackTrace();
            msg.setCode(1);
        }

        return msg;

    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @RequestMapping("/delUser")
    @ResponseBody
    public JsonResponseMessage shanUser(int id, String jgid, HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        User u = (User) session.getAttribute("info");
        try {
            Map<String, Object> map = userService.shanUser(id, jgid);
            if (map != null) {
                int codes = (int) map.get("code");
                if (0 == codes) {
                    msg.setCode(0);
                    msg.setData(map.get("userList"));
                    logger.info("删除用户成功：执行人：" + u.getUserName());
                } else if (2 == codes) {
                    msg.setCode(2);
                    msg.setMsg("已执行过删除操作!");
                    logger.info("執行過該操作" + u.getUserName());
                }

            } else {
                msg.setCode(1);
                msg.setMsg("删除失败请检查网络后重试!");
            }
        } catch (Exception e) {
            msg.setCode(1);
            msg.setMsg("删除失败请检查网络后重试!");
            logger.error("e.getStackTrace()");
        }
        return msg;

    }

    /**
     * 重置密码
     *
     * @param user
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public JsonResponseMessage updateUser(User user) {
        JsonResponseMessage msg = new JsonResponseMessage();
        user.setPassWord(MD5.password("123456"));
        int bs = userService.gengUser(user);
        if (bs != 0) {
            msg.setCode(0);
        } else {
            msg.setCode(1);
        }
        return msg;

    }

    /**
     * 得到所有用戶
     *
     * @param user
     * @return
     */
    @RequestMapping("/findAll")
    @ResponseBody
    public JsonResponseMessage findAllUser(User user, HttpSession session) {

        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            List<User> list = userService.findAllUser(user);
            if (list != null) {
                msg.setCode(0);
                msg.setData(list);

            } else {
                msg.setCode(1);
            }

        } catch (Exception e) {
            msg.setCode(1);
            e.printStackTrace();

        }
        return msg;

    }

    /**
     * 根據用戶名獲得用戶信息
     *
     * @param userName
     * @return
     */
    @RequestMapping("/findOne")
    @ResponseBody
    public JsonResponseMessage findOneUser(String userName) {
        JsonResponseMessage msg = new JsonResponseMessage();
        User u = userService.login(userName);
        if (u != null) {
            msg.setCode(0);
            msg.setData(u);
        } else {

            msg.setCode(1);
        }

        return msg;

    }

    /**
     * 修改密码
     *
     * @param oldpwd
     * @param newpwd
     * @param session
     * @return
     */
    @RequestMapping("/updataPassWord")
    @ResponseBody
    public JsonResponseMessage updataPassWord(String oldpwd, String newpwd, HttpSession session) {

        JsonResponseMessage msg = new JsonResponseMessage();
        User user = new User();
        User loginUser = (User) session.getAttribute("info");

        if (loginUser.getPassWord().equals(MD5.password(oldpwd))) {

            user.setId(loginUser.getId());
            user.setPassWord(MD5.password(newpwd));
            msg.setCode(0);
            userService.gengPassWord(user);

        } else {
            msg.setCode(50001);
            msg.setMsg("密码错误");
        }
        return msg;

    }

    /***
     * 修改用户所属机构和角色用
     * @param user
     * @return
     */
    @RequestMapping("/updateJG")
    @ResponseBody
    public JsonResponseMessage updateJG(User user, int[] array, HttpSession session) {
        User u = (User) session.getAttribute("info");
        JsonResponseMessage msg = new JsonResponseMessage();
        List<User> list = userService.gengJG(user, array);
        if (list != null) {
            msg.setCode(0);
            msg.setData(list);
            logger.info("修改用户机构或角色成功；执行人：" + u.getUserName());
        } else {
            logger.info("修改用户机构或角色失败；执行人：" + u.getUserName());
            msg.setCode(1);

        }

        return msg;
    }


    /**
     * 记住我
     *
     * @param
     * @return
     */
    @RequestMapping("/toRemember")
    @ResponseBody
    public String dealWithAlarm() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        // 判断是否登录过
        if (subject.getPrincipals() != null) {
            // 判断作用域里是否有用户
            if (session.getAttribute("info") == null) {
                Object prinvipal = subject.getPrincipal();
                if (prinvipal != null) {
                    String account = prinvipal.toString();
                    User user = userService.login(account);
                    session.setAttribute("info", user);
                }
            }
            return "1";
        }
        return "0";
    }

    /**
     * 得到所有用戶
     *
     * @param
     * @return
     */
    @RequestMapping("/list/myself")
    @ResponseBody
    public JsonResponseMessage findUser(HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        if (user != null) {
            User us = new User();
            try {
                us.setJgid(user.getJgid());
                List<User> list = userService.findAllUser(us);
                jsonResponseMessage.setRows(user.getId());
                jsonResponseMessage.setData(list);
                jsonResponseMessage.setCode(200);
            } catch (Exception e) {
                jsonResponseMessage.setCode(400);
                jsonResponseMessage.setMsg("服务器内部错误，请刷新重试");
            }
        } else {
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("网络连接中断，请重新登录进行尝试");
        }
        return jsonResponseMessage;
    }
}
